package cn.tedu._05mvcboot02.controller;

import cn.tedu._05mvcboot02.common.response.JsonResult;
import cn.tedu._05mvcboot02.mappers.UserMapper;
import cn.tedu._05mvcboot02.pojo.dto.Dto;
import cn.tedu._05mvcboot02.pojo.entity.User;
import cn.tedu._05mvcboot02.pojo.vo.UserListVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * RestController注解：
 * 组合注解：相当于   Controller + ResponseBody
 */
@Slf4j
//@Controller
@RestController
@RequestMapping("/v1/users/")
@Api("01.用户模块")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    /**
     * 1.添加用户功能
     */
    @ApiOperation("添加用户")
    @PostMapping(value = "insert")
    public JsonResult addUser(Dto dto){
        /*
            梳理业务逻辑,确定接口,以注册功能为例:
            1.接收客户端传递过来的数据;
            2.校验数据的合法性;
            3.确认用户名是否被占用[SELECT接口];
              3.1 被占用,return返回结束;
              3.2 未被占用,插入数据[INSERT接口];
              3.3 返回响应.
         */
        User user = new User();
        BeanUtils.copyProperties(dto,user);
        user.setCreated(new Date());
        userMapper.UserMapperInsert(user);
        return JsonResult.ok();
    }

    /**
     *
     * 查询列表
     */
    @ApiOperation("查询列表")
    @GetMapping("userList")
    public JsonResult userList(){
        List<UserListVO> userListVOS = userMapper.userList();
        return JsonResult.ok(userListVOS);
    }

    /**
     *删除指定用户
     */
    @ApiOperation("删除用户")
    @GetMapping("delete")
    @ApiImplicitParam(name="userid",value = "用户ID",required = true)
    public JsonResult userDelete(Long userid){
        if (userid<0){
            throw new IllegalArgumentException("ID值不能小于0");
        }
        log.debug("userid="+userid);
        userMapper.DeleteUser(userid);
        return  JsonResult.ok(userid);
    }
    @ApiOperation("修改列表")
    @PostMapping("update")
    public JsonResult updateUser(User user){
        userMapper.updateUser1(user);
        return JsonResult.ok(user);
    }
    /**
     * 根据用户ID查询指定用户信息
     */
    @ApiOperation("用户信息")
    @GetMapping("{id}")
    @ApiImplicitParam(name = "用户ID",value = "id",required = true)
    public JsonResult getUserById(@PathVariable("id")int id){
        User user = userMapper.selectById(id);
        return JsonResult.ok(user);
    }
}
